package LeetCode;

public class _21 {

    /**
     * 合并两个升序链表。
     *
     * @param l1
     * @param l2
     * @return
     */
    public ListNode mergeTwoLists1(ListNode l1, ListNode l2) {

        ListNode head = new ListNode(0, null);
        ListNode tail = head, tmp;
        while (l1 != null && l2 != null) {
            if (l1.val < l2.val) {
                tmp = l1;
                l1 = l1.next;
            } else {
                tmp = l2;
                l2 = l2.next;
            }
            tail.next = tmp;
            tail = tmp;
        }

        if (l1 != null)
            tail.next = l1;
        if (l2 != null)
            tail.next = l2;
        return head.next;
    }

    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        if (l1 == null)
            return l2;
        if (l2 == null)
            return l1;
        if (l1.val < l2.val) {
            l1.next = mergeTwoLists(l1.next, l2);
            return l1;
        }
        else {
            l2.next = mergeTwoLists(l2.next, l1);
            return l2;
        }
        }
        //错误版本。错在了：若1，2，3，4，和5，6，7，8，合并，结果为[1，5，]2，3，4，6，7，8
//        ListNode tmp = mergeTwoLists(l1.next, l2.next), res;
//        if (l1.val < l2.val) {
//            l2.next = tmp;
//            l1.next = l2;
//            res = l1;
//        } else {
//            l1.next = tmp;
//            l2.next = l1;
//            res = l2;
//        }
//        return res;
//    }
}
